import axios from 'axios'
import { Message ,Loading} from 'element-ui'
import router from '@/router'
import 'element-ui/lib/theme-chalk/index.css';
let loadingInstance = null
// import store from '@/store'

// 创建 axios 实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_APIS,
  // 超时
  timeout: 1200000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    let obj = config.url
    let arr = obj.split("/")
    let flag = false
    arr.map(res => {
      if (res == 'api') {
        flag = true
      }
    })
    console.info(flag)
    let  userinfo=JSON.parse(localStorage.getItem('tokenInfo'))
    console.info(userinfo)
    if (userinfo) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      if (flag && config.url.indexOf('/error/book/question/same') == -1 && config.url.indexOf('/jy/question/same') == -1 && config.url.indexOf('/jy/param/search') == -1 && config.url.indexOf('/jy/keyword/search') == -1 && config.url.indexOf('/jy/picture/ques/search') == -1 && config.url.indexOf('/jy/visit/num') == -1 && config.url.indexOf('/jy/ques/analyse') == -1) {
        config.headers.Authorization = userinfo.token;
        config.headers.uid = userinfo.uid
      }
    } else {
      if (config.url.indexOf('user_login2') == -1) {
        router.push('/login')
      }
    }
    // 获取当前路由
    if (router.currentRoute.path != '/confirmmain/generateinformation') {
      let options = {
        lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
      }
      loadingInstance = Loading.service(options);
    }
    
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  res => {
    if(res.data.msg=='权限不足'||res.data.msg=='token认证失败'){
      // localStorage.removeItem('token')
      sessionStorage.removeItem('tokenInfo')
      let path = router.history.current.path
      sessionStorage.setItem('urlPath',path)
      router.push({
        path:'/login'
      });
      Message.closeAll()
      Message.error({
        message:'登陆超时，请重新登陆'
      })
    }
     console.log(res.data.code,'ppppppppppppppppppppp');
     if (res.data.code != undefined &&res.data.code !== 0) {
      Message.error({
        message:res.data.msg
      })
     }
     if (router.currentRoute.path != '/confirmmain/generateinformation') {
       loadingInstance.close();
     }
    return res.data
  },
  error => {
    // 对响应错误做点什么
    Message.error(error.message || 'Request Error')
    
    // 特殊状态码处理
    if (error.response && error.response.status === 401) {
      store.dispatch('user/resetToken').then(() => {
        router.push('/login')
      })
    }
    
    return Promise.reject(error)
  }
)

export default service